<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Product_m extends CI_Model {
	function __construct()
    {
        parent::__construct();
    }
	
	 function getcategorylist($where = "") {
		
		
		$dates = $this->db->get_where('db_goods_category','rank=1')->result_array();
        foreach ($dates as $key => $rs) {
            if ($rs["rank"] == 1) {
                $dates[$key]["rankimg"] = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
            }
            $rankdates = $this->db->get_where('db_goods_category','rank=2 AND sort_id ='.$rs["id"].$where)->result_array();
            if ($rankdates) {
                foreach ($rankdates as $s => $rd) {
                    $rankdates[$s]["rankimg"] = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;┣";
                }
                $dates[$key]["rankdates"] = $rankdates;
                foreach ($rankdates as $s => $rd) {
                    $rankthree = $this->db->get_where('db_goods_category','rank=3 AND sort_id ='.$rd["id"].$where)->result_array();
                    if ($rankthree) {
                        foreach ($rankthree as $k => $res) {
                            $rankthree[$k]["rankimg"] = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;┣";
                        }

                        $dates[$key]["rankdates"][$s]["rankthree"] = $rankthree;
                    }
                }
            } else {
                $dates[$key]["rankdates"] = "";
            }
        }
        return $dates;
    }

	function editparent($id)
	{

		
 		$postdata['p_parent_name']	= $this->input->post('goods_name');
		$postdata['p_en_goods_name']	= trim(addslashes($this->input->post('en_goods_name')));
		$postdata['p_bigclassid']	= $this->input->post('bigclassID');
		$postdata['p_secondclassid']= $this->input->post('secondclassID');
		$postdata['p_threeclassid'] = $this->input->post('ThreeclassID');
		$postdata['p_goods_brand'] = $this->input->post('goods_brand');
		$postdata['p_costprice']	= $this->input->post('costprice');
		$postdata['p_procurement']  = $this->input->post('procurement')?$this->input->post('procurement'):15;
		$postdata['p_inventory_day']= $this->input->post('inventory_day')?$this->input->post('inventory_day'):15;
		$postdata['p_weight']		= $this->input->post('weight')?$this->input->post('weight'):400;
		$postdata['p_sellprice']	= $this->input->post('sellprice');
		$postdata['p_pd_length']	= $this->input->post('pd_length');
		$postdata['p_pd_width']		= $this->input->post('pd_width');
		$postdata['p_pd_height']	= $this->input->post('pd_height');
		$postdata['p_pd_declare_value']= $this->input->post('pd_declare_value');
		$postdata['p_goodstypeID']	= $this->input->post('goodstypeID');
		//$postdata['p_sale_status']  = $this->input->post('sale_status');
		$postdata['p_checkman']	= $this->input->post('checkman');
		$postdata['p_buyer']  = $this->input->post('buyer');
		$postdata['p_supplier']  =addslashes($this->input->post('supplier'));
		$postdata['standard']	= $this->input->post('standard');
		$postdata['memo']  = addslashes($this->input->post('memo'));
		$postdata['fabricinfo']  = addslashes($this->input->post('fabricinfo'));
		$postdata['wages']  = $this->input->post('wages')?$this->input->post('wages'):0;
		$postdata['bulkprice']  = $this->input->post('bulkprice')?$this->input->post('bulkprice'):0;
		
		if($this->input->post('businessman')){
			$postdata['businessman']	= $this->input->post('businessman');
			$postdata['businessmanline']  = $this->input->post('businessmanline');
		}
			//更新母商品
		$this->db->update('db_goods_parent', $postdata, 'p_parent_id=' . $id);
		
		//更新所有的供货商
		$p_supplier  =$this->input->post('supplier');
		if($p_supplier){
			$this->db->update("db_goods",array("g_supplier"=>$p_supplier),"goods_parentID='".$id."'");
		}
		

		//更新日志
		$p_buyer  =$this->input->post('buyer');
		$checkman  =$this->input->post('checkman');
		$rsGoods  = $this->db->get_where("db_goods"," goods_parentID = '".$id."'")->result_array();
		foreach($rsGoods as $key=>$rs)
		{
			$content="";
			if($rs["g_buyer"] !=$p_buyer)
			{
				$content.="原采购:".$rs["g_buyer"]." 批量更新为:".$p_buyer."<br>";
			}
			if($rs["g_checkman"] !=$checkman)
			{
				$content.="原开发:".$rs["g_checkman"]." 批量更新为:".$checkman."<br>";
			}
		
			if($content)
			{
				$this->fun->goods_update_log($rs["goods_id"],$content,1);
			}
		}
		if($p_buyer){
			$this->db->update("db_goods",array("g_buyer"=>$p_buyer),"goods_parentID='".$id."'");
		}
		
		if($checkman){
			$this->db->update("db_goods",array("g_checkman"=>$checkman),"goods_parentID='".$id."'");
		}
		
		$standard  =$this->input->post('standard');
		if($standard){
			$this->db->update("db_goods",array("standard"=>$standard),"goods_parentID='".$id."'");
		}

		$fabricinfo  =$this->input->post('fabricinfo');
		if($fabricinfo){
			$this->db->update("db_goods",array("fabricinfo"=>$fabricinfo),"goods_parentID='".$id."'");
		}
	

		$p_inventory_day =$this->input->post('inventory_day');
		$p_procurement =$this->input->post('procurement');
		if($p_inventory_day){
			$this->db->update("db_goods",array("g_inventory_day"=>$p_inventory_day,"g_procurement"=>$p_procurement),"goods_parentID='".$id."'");
		}
		
		
		
		


		return $id;
	}
	function saveparent()
	{
		//先判断是否存在！
		$sku = trim($this->input->post('sku'));
		$sku = str_replace(" ", "", $sku); //替换空
		$rs = $this->fun->getdatabasesdetail('db_goods_parent'," AND p_parent_sku='".$sku."'");
		if($rs)
		{
			die('SKU已经存在！');
		}

		//如果供应商信息存在！需要保存
		$businessman = $this->input->post('businessman');
		$businessmanline = $this->input->post('businessmanline');
		if($businessman)
		{
			$businessman = serialize($businessman);
			$businessmanline = serialize($businessmanline);

		}
		
		$postdata['p_parent_sku']	= strtoupper($sku);	//全部大写
		$postdata['p_parent_name']	= $this->input->post('goods_name');
		$postdata['p_en_goods_name']	= trim(addslashes($this->input->post('en_goods_name')));
		$postdata['p_bigclassid']	= $this->input->post('bigclassID');
		$postdata['p_secondclassid']= $this->input->post('secondclassID');
		$postdata['p_threeclassid'] = $this->input->post('ThreeclassID');
		$postdata['p_goods_brand'] = $this->input->post('goods_brand');
		$postdata['p_costprice']	= $this->input->post('costprice');
		$postdata['p_procurement']  = $this->input->post('procurement')?$this->input->post('procurement'):15;
		$postdata['p_inventory_day']= $this->input->post('inventory_day')?$this->input->post('inventory_day'):15;
		$postdata['p_weight']		= $this->input->post('weight')?$this->input->post('weight'):400;
		$postdata['p_sellprice']	= $this->input->post('sellprice');
		$postdata['p_pd_length']	= $this->input->post('pd_length');
		$postdata['p_pd_width']		= $this->input->post('pd_width');
		$postdata['p_pd_height']	= $this->input->post('pd_height');
		$postdata['p_pd_declare_value']= $this->input->post('pd_declare_value');
		$postdata['p_goodstypeID']	= $this->input->post('goodstypeID');
		$postdata['p_sale_status']  = $this->input->post('sale_status')?$this->input->post('sale_status'):1;
		$postdata['p_checkman']	= $this->input->post('checkman');
		$postdata['p_buyer']  = $this->input->post('buyer');
		$postdata['p_supplier']  =addslashes($this->input->post('supplier'));
		$postdata['standard']	= addslashes($this->input->post('standard'));
		$postdata['memo']  = addslashes($this->input->post('memo'));
		$postdata['fabricinfo']  = addslashes($this->input->post('fabricinfo'));
		$postdata['wages']  = $this->input->post('wages')?$this->input->post('wages'):0;
		$postdata['bulkprice']  = $this->input->post('bulkprice')?$this->input->post('bulkprice'):0;
		$postdata['businessman']	=$businessman;
		$postdata['businessmanline']=$businessmanline;
		$where = array('p_parent_sku' => $sku);
		$rsdb = $this->db->get_where('db_goods_parent',$where)->result_array();
		if(count($rsdb)==0)	//没有母商品
		{
			$postdata['p_intime']		=time();
			$postdata['p_updatetime']	=date("Y-m-d H:i:s");
			$postdata['p_createID']		=$_COOKIE["userid"];
			$postdata['p_createUser']	=$_COOKIE["username"];
			$this->db->query($this->db->insert_string('db_goods_parent', $postdata));
			$parentID = $this->db->insert_id();
		}else{
			//更新母商品
			$this->db->update('db_goods_parent', $postdata, 'p_parent_id=' . $rsdb[0]["p_parent_id"]);
			$parentID = $rsdb[0]["p_parent_id"];
		}

		


		return $parentID;
	}
	
	function savegoods($parentID,$goods_id='')
	{
	
		
		$subsku =  $this->input->post('subsku');

		$postdata["goods_parentID"] = $parentID;
		$parentList = $this->db->get_where('db_goods_parent','p_parent_id='.$parentID)->result_array();
		$postdata['goods_parent_sku']	= $parentList[0]["p_parent_sku"];
		$postdata['goods_name']	= $this->input->post('goods_name');
		$postdata['g_bigclassid']	= $this->input->post('bigclassID');
		$postdata['g_secondclassid']= $this->input->post('secondclassID');
		$postdata['g_threeclassid'] = $this->input->post('ThreeclassID');
		$en_goods_name = $this->fun->ReplaceSpecialChar(trim($this->input->post('en_goods_name')));
		$postdata['en_goods_name']	= $en_goods_name;
		$postdata['goods_brand']	= trim($this->input->post('goods_brand'));
		$postdata['g_costprice']	= $this->input->post('costprice');
		$postdata['g_procurement']  = $this->input->post('procurement');
		$postdata['g_inventory_day']= $this->input->post('inventory_day');
		$postdata['g_weight']		= $this->input->post('weight');
		$postdata['g_sellprice']	= $this->input->post('sellprice');
		$postdata['g_pd_length']	= $this->input->post('pd_length')?$this->input->post('pd_length'):0;
		$postdata['g_pd_width']		= $this->input->post('pd_width')?$this->input->post('pd_width'):0;
		$postdata['g_pd_height']	= $this->input->post('pd_height')?$this->input->post('pd_height'):0;
		$postdata['g_pd_declare_value']= $this->input->post('pd_declare_value');
		$postdata['g_goodstypeID']	= $this->input->post('goodstypeID');
		if( $this->input->post('sale_status')){
			$postdata['g_sale_status']  = $this->input->post('sale_status');
		}
		if($goods_id=="")
		{
			$postdata['g_updatetime']	=date("Y-m-d H:i:s");
			$postdata['g_createID']		=$_COOKIE["userid"];
			$postdata['g_createUser']	=$_COOKIE["username"];
		}
		
		$postdata['g_checkman']	= $this->input->post('checkman');
		$postdata['g_buyer']  = $this->input->post('buyer');
		$postdata['standard']	= $this->input->post('standard');
		$postdata['g_supplier']  = addslashes($this->input->post('supplier'));
		$postdata['memo']  =addslashes($this->input->post('memo'));
		$postdata['fabricinfo']  = addslashes($this->input->post('fabricinfo'));
		$postdata['wages']  = $this->input->post('wages')?$this->input->post('wages'):0;
		$postdata['bulkprice']  = $this->input->post('bulkprice')?$this->input->post('bulkprice'):0;
		

		
		
		if($this->input->post('cognatelist'))
		{
			if($goods_id)
			{
				//子SKU
				$cognatelist = $this->fun->myTrim($this->input->post('cognatelist'));//去空格
				if($cognatelist)
				{
					$costr = $this->fun->iscognatelist($cognatelist,$goods_id);
					if( $costr != false)
					{
                        echo $costr;
						die;
					}
				}
				$goodsinfo = $this->fun->getdatabasesdetail('db_goods'," AND goods_id = '".$goods_id."'");
				if($goodsinfo['cognatelist']=='')
				{
					$postdata['cognatelist']  = ",".$cognatelist.",";
				}else{
					$postdata['cognatelist']  = $cognatelist;
				}

				$len = strlen($postdata['cognatelist']);
				
				if(substr($postdata['cognatelist'],$len-1) !=',')
				{
					$postdata['cognatelist']  = $postdata['cognatelist'].",";
				}
				if(substr($postdata['cognatelist'],0,1) !=',')
				{
					$postdata['cognatelist']  = ",".$postdata['cognatelist'];
				}

				
			}
		}else{
			$postdata['cognatelist']  = "";
		}
	
				
		
	
		if(count($subsku)>0)	//填写了子类商品
		{
		/*******************
			获取外采购商品开发人员对应的仓库
		*********************/
		$str_warehouse = $this->config->item('temporary_warehouse');
		$arr_warehouse = explode("\n",$str_warehouse);
		$arr_persons = array(); //维护人员
		$arr_positions = array();//具体仓库位置
		foreach($arr_warehouse as $k=>$v){
			$arr_value = explode("|",trim($v));
			$arr_persons[$k] = $arr_value[0];
			$arr_positions[$k]=$arr_value[1];
		}
		$protector =  $this->input->post('checkman');
		$positions = "";
		if(in_array($protector,$arr_persons)){
			$key = array_search($protector,$arr_persons);
			$positions = $arr_positions[$key]; //仓库位置
		}
		/*******获取临时仓位结束**********/
			$subsku = array_unique(array_filter($subsku));
			foreach($subsku as $key=>$rs)
			{
				$rs = str_replace(" ", "", $rs); //替换空
				$rs = str_replace(",","",$rs);
				$rs = str_replace("'","",$rs);
				$postdata["goods_sku"] = trim(strtoupper($rs));

				$costr = $this->fun->iscognatelist(trim(strtoupper($rs)));
				if( $costr != false)
				{
					echo $costr;
					die;
				}

				$rs = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".trim(strtoupper($rs))."'");
				if($rs)
				{
					continue;//如果存在sku则不保存
				}
				$this->db->query($this->db->insert_string('db_goods', $postdata));
				$goods_id = $this->db->insert_id();
				$this->fun->goods_update_log($goods_id,$_COOKIE["username"].'添加新商品',1);	//更新商品信息
				if( $_FILES["userfile"]["name"][$key]){
					$resdb = $this->fun->saveImages($goods_id,$key);	//保存图片
					if($resdb["st"]==200)$this->fun->goods_update_log($goods_id,'更新商品图片',1);	//更新商品信息
				}else{	//如果不上传图片，即继承原来商品图片
							/*****如果有图片，需要更新图片*****/
						$resgoodsImages = $this->fun->getdatabasesdetail('db_goods', " AND goods_sku = '" .strtoupper(trim($this->input->post('sku'))). "'", 'goods_id');
						if( $resgoodsImages["goods_id"])
						{
							$goodsImages = $this->db->limit(3)->order_by('id',"ASC")->get_where('db_goods_images',"goods_id='".$resgoodsImages["goods_id"]."'")->result_array();
							if($goodsImages)
							{
								foreach($goodsImages as $k=>$r)
								{
									$Imgdata = "";
									$Imgdata["goods_id"] = $goods_id;
									$Imgdata["images_type"] = 1;
									$Imgdata["images_url"] = $r["images_url"];
									$Imgdata["local_url"] = $r["local_url"];
									$Imgdata["thumb_url"] = $r["thumb_url"];
									$Imgdata["filename"] = $r["filename"];
									$Imgdata["filesize"] = $r["filesize"];
									$Imgdata["createUser"] = $r["createUser"];
									$Imgdata["instime"] = $r["instime"];
									$this->db->insert("db_goods_images",$Imgdata);
								}
							}
							$this->fun->goods_update_log($goods_id,'继承更新商品图片',1);
						}
				}

				//默认仓库
				if($this->config->item('defaultstorage'))
				{
					/******如果是开发人员，自动新建临时仓位******/
				
					 $defaultstorage = explode("|",$this->config->item('defaultstorage'));
					 foreach($defaultstorage as $k=>$storage)
					 {
						$this->fun->savestock($goods_id,$storage,0,0,$positions);	//保存库存
					 }
				}
				/********保存属性**************************/
				if($this->input->post('goodstypeID'))
				{
					$goodstype = $this->db->get_where('db_attribute','cat_id='.$this->input->post('goodstypeID'))->result_array();
					foreach($goodstype as $s=>$red)
					{
						$strdata[$s]["attr_id"] = $red["attr_id"];
						$attrID = $red['attr_id'];
						$attrvalue = $this->input->post("attr_values$attrID");
						$strdata[$s]["str"] = $attrvalue[$key];
					}
				}
				
				
				foreach($strdata as $s=>$red)
				{
					if($red['str']){
					$newpost["goods_id"] = $goods_id;
					$newpost["attr_id"]  = $red['attr_id'];
					$newpost["attr_value"] =$red['str'];
					$this->db->query($this->db->insert_string('db_goods_attr', $newpost));
					}
				}
				/*************保存属性结束****************/

				/*************保存商品采购信息开始****************/
					$this->savebusinessman($parentID,$goods_id,$postdata["goods_sku"]);
				/*************保存商品采购信息结束****************/
				
			}
			
		}else{
			if($goods_id)
			{
				
				//获取到
				if($this->input->post('goodstypeID'))
				{
					$goodstype = $this->db->get_where('db_attribute','cat_id='.$this->input->post('goodstypeID'))->result_array();
					foreach($goodstype as $s=>$red)
					{
						$strdata[$s]["attr_id"] = $red["attr_id"];
						$attrID = $red['attr_id'];
						$attrvalue = $this->input->post("selectvaluelist$attrID");
						$strdata[$s]["str"] = $attrvalue;
					}
					foreach($strdata as $s=>$red)
					{
						
						$newpost["goods_id"] = $goods_id;
						$newpost["attr_id"]  = $red['attr_id'];
						$newpost["attr_value"] =$red['str'];
						$rsdn = $this->fun->getdatabasesdetail('db_goods_attr'," AND goods_id='".$goods_id."' AND attr_id='".$red['attr_id']."'");
						if($rsdn)
						{
							if($red['str']=="")
							{
								 $this->db->delete('db_goods_attr', 'goods_attr_id=' . $rsdn['goods_attr_id']);
							}else{
								 $this->db->update('db_goods_attr', $newpost, 'goods_attr_id=' . $rsdn['goods_attr_id']);
							}
						}else{
							$this->db->query($this->db->insert_string('db_goods_attr', $newpost));
						}
						
					}
				}
			
				//$rsSKU = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".trim($rs)."'");
				
				
				$sku = str_replace(" ", "", $this->input->post('sku')); //替换空
				$sku = str_replace("　", "", $this->input->post('sku')); //替换空
				if($_COOKIE['userid']==295 || $_COOKIE['userid'] == 155 || $_COOKIE['userid'] == 145){
					$postdata["goods_sku"] = trim($sku);
				}
				
				
				
				$this->savebusinessman($parentID,$goods_id,trim($sku));

			    $rval = $this->fun->updatelog('db_goods',$postdata,'goods_id=' . $goods_id,$this->status,$goods_id);
			   	$this->db->update('db_goods', $postdata, 'goods_id=' . $goods_id);
				if($rval)
				$this->fun->goods_update_log($goods_id,$rval,1);	//更新商品信息
				

			}else{
				$postdata["goods_sku"] = $parentList[0]["p_parent_sku"];
				$rs = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".trim($parentList[0]["p_parent_sku"])."'");
				if($rs)
				{
					die("存在重复SKU，请先设置子SKU名称");//如果存在sku则不保存
				}
				
				$this->db->query($this->db->insert_string('db_goods', $postdata));
				$goods_id = $this->db->insert_id();
				/*************保存商品采购信息开始****************/
				$this->savebusinessman($parentID,$goods_id,$postdata["goods_sku"]);
				/*************保存商品采购信息结束****************/

				/***********新建仓库************/
				//默认仓库
				if($this->config->item('defaultstorage'))
				{
					 $defaultstorage = explode("|",$this->config->item('defaultstorage'));
					 foreach($defaultstorage as $k=>$storage)
					 {
						$this->fun->savestock($goods_id,$storage,0,0);	//保存库存
					 }
				}
				$this->fun->goods_update_log($goods_id,'添加新商品',1);	//更新商品信息
			}
		}

	}


	public function savebusinessman($parentID,$goods_id,$goods_sku)
	{
		
		//如果供应商信息存在！需要保存
		$businessman = $this->input->post('businessman');
		$businessmanline = $this->input->post('businessmanline');
		if($businessman)
		{
			foreach($businessman as $key=>$rs)
			{
				$post="";
				$post['goods_id'] = $goods_id;
				$post['goods_sku'] = $goods_sku;
				$post['parentID'] = $parentID;
				$post['businessman'] = $rs;
				$post['businessmanline'] = addslashes($businessmanline[$key]);
				$res = $this->fun->getdatabasesdetail("db_goods_purchasing"," AND goods_id = '".$goods_id."' AND businessmanline = '".$post['businessmanline']."'");
				if($res)
				{
					$this->db->update('db_goods_purchasing', $post, 'id=' . $res['id']);
				}else{
					$this->db->insert('db_goods_purchasing', $post);
				}

			}

		}
		return true;
		/*
		$rsdb = $this->fun->getdatabasesdetail("db_goods_parent"," AND p_parent_id = '".$parentID."'");
		if($rsdb && $rsdb['businessman'])
		{
			$businessman = unserialize($businessman);
			$businessmanline = unserialize($businessmanline);
			
		}*/

			
	}
	
	public function savedoupload()
	{
		$goods_id = $this->input->post('goods_id');
		$goodsinfo = $this->fun->getdatabasesdetail('db_goods'," AND goods_id = '".$goods_id."'");
		$upload_path = 'uploads/goods/'.date("Ymd")."/".$goodsinfo['goods_parent_sku'];
		$dir = dirname(__FILE__) . "/../../".$upload_path;
		!is_dir($dir) && @mkdir($dir, 0755, true);
		$this->db->trans_begin();
		$msg = $this->fun->uploadfile($upload_path,$goods_id,'goods');
		if($msg["st"] == 200)
		{
			$filename = $msg["filename"];
			$nums = count($filename);
			for($i=1;$i<=$nums;$i++)
			{
				$imgdata["goods_id"] = $goods_id;
				$imgdata["images_type"] = 1;
				$imgdata["images_url"] = $msg["filename"][$i][0];
				$imgdata["local_url"] = $msg["filename"][$i][2];
				$imgdata["filename"] = $msg["filename"][$i][0];
				$imgdata["filesize"] = $msg["filename"][$i][1];
				$imgdata["thumb_url"] = $msg["filename"][$i][3];
				$imgdata["createUser"] = $_COOKIE["username"];
				$imgdata["instime"] = time();
				if($msg["filename"][$i][0]!=3000003)
				{
					
					$this->db->query($this->db->insert_string('db_goods_images', $imgdata));
				}
			}

			$this->fun->goods_update_log($goods_id,'上传商品图片',1);	//更新商品信息
			if ($this->db->trans_status() === FALSE)
			{
				$this->db->trans_rollback();
			}
			else
			{
				$this->db->trans_commit();
			}
		}
		return $msg;
	}
	
	function goodscategory($id)
	{
		$res = $this->db->get_where('db_goods_category','id='.$id)->result_array();
		if($res[0]["cate_name"])
		{
			return $res[0];
		}

	}
	function getallstock($pid)
	{
		$goods_id = $this->fun->getdatabasesdetail("db_goods"," AND goods_parentID='".$pid."'"," GROUP_CONCAT(goods_id) as goods_id");
		$stock = $this->fun->getdatabasesdetail("db_goods_stock A left join db_storage B on A.storage_id = B.id "," AND  goods_id IN ($goods_id[goods_id]) and stock>0  AND B.is_show = 1"," SUM(stock) as stock");
		$sale = $this->fun->getdatabasesdetail("db_goods "," AND  goods_id IN ($goods_id[goods_id]) "," SUM(saleNum) as saleNum");
		$salenum = $sale['saleNum']?$sale['saleNum']:0;
		$stock = $stock["stock"]?$stock["stock"]:0;
		return array("salenum"=>$salenum,"allstock"=>$stock);
	}
	function getsalesku($newgoods_sku="")
	{
		$sku = $this->fun->randCode(999).$this->fun->randCode(999).$newgoods_sku;
	
		$rsdb = $this->fun->getdatabasesdetail('db_salesku' ," AND autosku='".$sku."'");
		if($rsdb)
		{
			$this->getsalesku($newgoods_sku);
		}else{
			return $sku;
		}
	}

	function savestatus($pid,$t=0,$status,$proudctcate=0)
	{
		
		if($t ==1)
		{

			$this->db->trans_begin();
			$goods = $this->db->get_where('db_goods'," goods_parentID='".$pid."'")->result_array();
			if(count($goods)>0)
			{
				
				foreach($goods as $key=>$rs){
				 $postdata["g_sale_status"] = $status;
				
				 $rval = $this->fun->updatelog('db_goods',$postdata,'goods_id=' . $rs["goods_id"],$this->status,$rs["goods_id"]);
				
				 if($rval)$this->fun->goods_update_log($rs["goods_id"],$rval,1);	//更新商品信息
				}
			}
			//更新parent表且必须更新goods表
			if($_COOKIE["userid"]==295)
			{
				$this->db->update('db_goods_parent', array("p_sale_status"=>$status,"p_yz"=>0), 'p_parent_id=' . $pid);
				$this->db->update('db_goods', array("g_sale_status"=>$status,"yz"=>0), "goods_parentID='".$pid."' ");
			}else{
				$this->db->update('db_goods_parent', array("p_sale_status"=>$status), 'p_parent_id=' . $pid);
				$this->db->update('db_goods', array("g_sale_status"=>$status), "goods_parentID='".$pid."' AND   g_sale_status !=5 AND g_sale_status !=4");
			}
			
			if($proudctcate>0)
			{
				if($proudctcate==4)
				{
					$proudctcate=0;
				}
				$this->db->update('db_goods', array("g_sale_cate"=>$proudctcate), 'goods_parentID=' . $pid);
			}else{
				$this->db->update('db_goods', array("g_sale_cate"=>0), 'goods_parentID=' . $pid);
			}
			//更新统计信息
			$this->fun->insertsysstatistical('status',$status,$pid,1,$this->status);
		
			if ($this->db->trans_status() === FALSE)
			{
				$this->db->trans_rollback();
			}
			else
			{
				$this->db->trans_commit();
			}
			

		}else{
			//只更新pid这条数据,不能修改清仓和停售的商品
			$this->db->update('db_goods', array("g_sale_status"=>$status), "goods_id='". $pid."' AND g_sale_status !=5 AND g_sale_status !=4 ");
		}
		
	}

	function getproductlist($database, $where, $page = 1, $if_csv = 0, $pageSize = 100, $orderbys = '') {
		 
      
       // $sql = "SELECT * FROM  $database WHERE 1";
       // $sql .= $where;

		if($_COOKIE['ext_userid'])
		{
			if($_COOKIE['ext_userid_open_goods'] == 1)	//允许查看自己组和非其他组的商品
			{
				
				$externalList = $this->fun->getdatabasesdetail('d_user_external'," AND id !='".$_COOKIE['external_id']."'",'GROUP_CONCAT(external_userID) as Createid');
				$ext_userID = $externalList['Createid'];
			
				$where.=" AND (p_createID not in ($ext_userID))";
			}else{
				//只能查看其他组
				$ext_userID = $_COOKIE['ext_userid'];
				$where.=" AND (p_createID in ($ext_userID) or p_checkman like '".$_COOKIE["username"]."')";
			}
			
		
		}else{
			if($_COOKIE["department"] == 1 || $_COOKIE["classid"] == 11 || $_COOKIE["classid"] == 10 || $_COOKIE["userid"] == 144){
			}else{

				$notext_userID = $this->db->get_one("select GROUP_CONCAT(external_userID) as notex_userid from d_user_external where 1 and is_stop = 0");
				$notext_userID = $notext_userID['notex_userid'];
				//$notext_userID = $_COOKIE['notext_userid'];
				if($notext_userID){
					$where.=$where." AND p_createID not in ($notext_userID)";
				}
			}
		}
        if ($page != null) {
            $offset = ($page - 1) * $pageSize;
            $limit = " LIMIT $pageSize OFFSET $offset";
        }
		
		$sel = "select S.goods_sku,SP.p_parent_sku,SP.p_parent_name,SP.p_bigclassid,SP.p_secondclassid,SP.p_threeclassid,SP.p_parent_id,SP.p_sale_status,SP.p_supplier ";
        $from = " from db_goods_parent SP left join db_goods S  on S.goods_parent_sku = SP.p_parent_sku $forms";
		$yzsql=" S.yz=0";


		if($this->config->item('isopenclosedgoods') ==0){	//管理员可见
			if( $_COOKIE['department']==1)
			{
				//管理员和主管可以看到停售的商品
				$yzsql= "  (S.yz=0 or S.yz = 2) ";
			}else{
				$yzsql=" S.yz=0";
			}
		}elseif($this->config->item('isopenclosedgoods') ==1){	// 管理员和主管可见
			if( $_COOKIE['department']==1 ||  $_COOKIE['department'] == 2)
			{
				$yzsql= "  (S.yz=0 or S.yz = 2) ";
			}else{
				$yzsql=" S.yz=0";
			}
		}elseif($this->config->item('isopenclosedgoods') ==2){	//所有人可见
				$yzsql= "  (S.yz=0 or S.yz = 2) ";
		}else{
			//所有人不可见
			$yzsql=" S.yz=0";
		}
			
	
		
		$wheres .= " where 1 $where AND {$yzsql} " . $sql . " group by SP.p_parent_id ";
        
		if($if_csv==1)
		{
			$sql =   $sel."  " . $from . $wheres  .$having.$orderbys;
		}else{
			$sql =   $sel."  " . $from . $wheres  .$having.$orderbys. $limit;
		}
		$wheresql = $sql;
		
		$query = $this->db->query($wheresql);
        $dates = $query->result_array();

        $sqlCount =  $sel . $from . $leftjoin . $wheres.$having.$orderbys;
        $query2 = $this->db->query($sqlCount);
        $allCount = $query2->num_rows();
		
        return array('list' => $dates, 'total' => $allCount);
	
	}
	
	/*******
	*** 获取工厂信息
	***	
	********/
	function getfactory()
	{
		return $factory = $this->db->get('db_factory')->result_array();
	}

	/********
	** 保存新品开发信息
	**
	********************/
	function saveNewProduct()
	{
		$id =  trim($this->input->post('id'));
		$postdata["sku"]  = trim($this->input->post('sku'));
		$postdata["name"] = trim($this->input->post('name'));
		$postdata["en_name"] = trim($this->input->post('en_name'));
		$postdata["supplier"] = trim($this->input->post('supplier'));
		$postdata["suppliername"] = trim($this->input->post('suppliername'));
		$postdata["contect"] = trim($this->input->post('contect'));
		$postdata["weburl"] = trim($this->input->post('weburl'));
		$postdata["saleprice"] = trim($this->input->post('saleprice'));
		$postdata["gender"] = $this->input->post('gender')?$this->input->post('gender'):1;
		$postdata["tbopertime"] = trim($this->input->post('tbopertime'));
		$postdata["memo"] = trim($this->input->post('memo'));
		$postdata["status"] = 1;

		//判断是否有外采购sku存在
		$externalSku = trim($this->input->post('externalSku'));
		if($externalSku){
			$this->db->update("db_external_buy",array("goods_code"=>$postdata["sku"])," sku = '".$externalSku."'");
		}

		if($id)
		{
			$this->db->update('db_product_develop',$postdata," id='".$id."'");
			return $id;
		}else{
			$postdata["createName"] = $_COOKIE["username"];
			$postdata["instime"] = date("Y-m-d H:i:s");
			$this->db->insert('db_product_develop', $postdata);
			$id = $this->db->insert_id();
		}
		

		if($postdata["supplier"] == 1)$taskerman = $this->config->item('factory1audit');
		if($postdata["supplier"] == 2)$taskerman = $this->config->item('factory2audit');
		if($postdata["supplier"] == 3)$taskerman = $this->config->item('outsidepurchasing');
		if($postdata["supplier"] == 7)$taskerman = $this->config->item('factory7audit');
		//设置系统Message提醒
		if($taskerman && $this->config->item('productdevelopopen')==1)
		{
				$randid = $this->message->getMessageNums();	//获取当前存储的条数	
				$packingman = explode("|",$taskerman);
				foreach($packingman as $rs)
				{
					$postMessageData["message_type"] = $this->message->getMessageType(5);	//【新品开发】初审
					$postMessageData["message"] = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."添加了新品开发需求,等待初审"; //消息内容
					$postMessageData["message_toName"] = $rs;	//接收对象姓名
					$postMessageData["isread"] =  $randid;				//同条消息标识
					$postMessageData["url"] = "/product/newproduct?id={$id}";	//点击消息后返回连接
					$this->fun->saveMessage($postMessageData);
				}
			
		}
		return $id;
	}


	function saveProductImages()
	{
		$filepath = $this->input->post('filepath');
		$filethumbpath = $this->input->post('filethumbpath');
		if(count($filepath)>0)
		{
			foreach($filepath as $key=>$rs)
			{
				$thumb =  $filethumbpath[$key];
				$dir = dirname(__FILE__) . "/../..".$rs;
				$img = array();
				$img["uid"] = $this->input->post('MergeProductID');
				$img["images_url"] = $rs;
				$img["thumb_url"] = $thumb;
				$img["createUser"] = $_COOKIE["username"];
				$img["instime"] = time();
				$img["filename"] = basename($dir);
				$img["filesize"] = filesize($dir);
				$this->db->insert('db_productdevelop_images',$img);

			}
		}
		return $this->input->post('MergeProductID');

	}

	function getProductImages($id)
	{
		$result = $this->db->get_where('db_productdevelop_images', " uid = '".$id."'")->result_array();
		if(count($result)>0)
		{
			return $result;
		}
	}
	
	function getorderhistoryList($goodsid)
	{
		$orderby = " order by B.order_id DESC  LIMIT 0, ".$this->config->item('confighistoryordernum');
		$list = $this->fun->getdatabaseslist("db_order_sell A left join db_order_list B on A.order_id=B.order_id"," AND A.goods_id='".$goodsid."' AND B.order_status !=7 AND B.order_status !=6 ","B.*",$orderby);
		if(count($list)>0)
		{
			foreach($list as $key=>$rs)
			{
				$ordersn = $this->fun->getdatabasesdetail("db_order_batchexpress"," AND batch_order_sn = '".$rs['order_sn']."'");
				$list[$key]["expresstime"] = $ordersn['opertime'];
			}
		}
		return $list;
	}
	function getorderhistoryFBAList($goodsid)
	{
		$orderby = " order by B.id DESC  LIMIT 0, ".$this->config->item('confighistoryordernum');
		$list = $this->fun->getdatabaseslist("db_amzordertmpsell A left join db_amzordertmp B on A.ordertmpid=B.id"," AND A.goods_id='".$goodsid."' AND B.status =1","B.*",$orderby);
		foreach($list as $key=>$rs)
		{
			$list[$key]["expresstime"] =date("Y-m-d H:i:s", $rs['instime']);
		}
		return $list;
	}
	//Excel 导入新的SKU信息
	//1正常2开发期商品
	/**************************************************
	导入开发期的产品信息
	如：鞋子尺码太多，但很多鞋子是开发出来只卖出1、2个订单，SKU信息确很多，
	导入新产品时，保存所有的尺码信息到另外一个表，
	当销售达到一定量时，开放出所有的尺码信息，否则一直只留一个
	*****************************************************/
	function ImportNewProduct($upfile,$types=2)
	{
		if($resExcel = PHPExcel_IOFactory::load($upfile)){
		$allRow = $resExcel->getActiveSheet()->getHighestRow();

				$s = 0;
				
				for($i=2;$i<=$allRow;++$i){
					$postdata = "";
					$A=trim($resExcel->getActiveSheet()->getCell('A'.$i)->getValue());	//商品编号
					
					$A = $this->fun->myTrim($A);
					$A=strtoupper($A);
					if($A){
						$postdata["sku"] = $A;
						$postdata["goods_name"]=trim($resExcel->getActiveSheet()->getCell('B'.$i)->getValue());	//商品名称
						$postdata["en_goods_name"]=trim($resExcel->getActiveSheet()->getCell('C'.$i)->getValue());	//英文名称
						$bigclassID=trim($resExcel->getActiveSheet()->getCell('D'.$i)->getValue());	//大分类
						$secondclassID=trim($resExcel->getActiveSheet()->getCell('E'.$i)->getValue());	//小分类
						$postdata["g_costprice"]=trim($resExcel->getActiveSheet()->getCell('F'.$i)->getValue());	//成本价
						$postdata["g_weight"]=trim($resExcel->getActiveSheet()->getCell('G'.$i)->getValue());	//商品重量
						$postdata["businessman"]=trim($resExcel->getActiveSheet()->getCell('H'.$i)->getValue());	//采购商家
						$postdata["businessmanline"]=trim($resExcel->getActiveSheet()->getCell('I'.$i)->getValue());	//采购链接
						$postdata["g_procurement"]=trim($resExcel->getActiveSheet()->getCell('J'.$i)->getValue());	//采购天数
						$postdata["g_inventory_day"]=trim($resExcel->getActiveSheet()->getCell('K'.$i)->getValue());	//库存警戒天数
						$postdata["g_sellprice"]=trim($resExcel->getActiveSheet()->getCell('L'.$i)->getValue());	//零售价格
						$postdata["g_pd_declare_value"]=trim($resExcel->getActiveSheet()->getCell('M'.$i)->getValue());	//申报价值
						$postdata["g_buyer"]=trim($resExcel->getActiveSheet()->getCell('N'.$i)->getValue());	//采购员
						$postdata["g_checkman"]=trim($resExcel->getActiveSheet()->getCell('O'.$i)->getValue());	//质检员
						$postdata["standard"]=trim($resExcel->getActiveSheet()->getCell('P'.$i)->getValue());	//质检标准
						$postdata["fabricinfo"]=trim($resExcel->getActiveSheet()->getCell('Q'.$i)->getValue());	//面料信息
						$postdata["memo"]=trim($resExcel->getActiveSheet()->getCell('R'.$i)->getValue());	//备注信息
						$postdata["cognatelist"]=trim($resExcel->getActiveSheet()->getCell('S'.$i)->getValue());	//子SKU
						$postdata["imagesUrl"]=trim($resExcel->getActiveSheet()->getCell('T'.$i)->getValue());	//图片链接地址
						
						$rsdbClass =  $this->fun->getdatabasesdetail("db_goods_category"," AND cate_name = '".$bigclassID."' and sort_id = 0");
						if($rsdbClass)
						{
							$postdata["bigclassID"] = $rsdbClass['id'];
						}else{
							$postdata["bigclassID"] = 43;
						}

						$rsdbClassCl =  $this->fun->getdatabasesdetail("db_goods_category"," AND cate_name = '".$secondclassID."' AND sort_id = '".$rsdbClass['id']."'");
						if($rsdbClassCl)
						{
							$postdata["secondclassID"] = $rsdbClassCl['id'];
						}else{
							$postdata["secondclassID"] =44;
						}
					}
					
					
				
					if($A)
					{
						$rsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_sku='".$A."'"); //不存在则更新SKU
						if(!$rsdb)
						{
							$goodsno =  $A;
							//判断是否包含-
							$expgoodsno = explode("-",trim($goodsno));
							if(count($expgoodsno)>=2){
								$parent_goods = $expgoodsno[0];
							}else{
								$parent_goods = trim($goodsno);
							}
							
							$this->load->library('Formmabangsku');
							if($types==2){
								$goods_id = $this->formmabangsku->getNewsaveParent($parent_goods,$postdata);//传入一个SKU如果父SKU存在，则返回ID，不存在则创建
							}else{
								//开发期商品
								$goods_id = $this->formmabangsku->saveDevelopmentParent($parent_goods,$postdata);//传入一个SKU如果父SKU存在，则返回ID，不存在则创建
							}
							echo $A;
							echo "->";
							echo $goods_id;
							echo "<br>";
						}
					}
				}
			}
	}
	
	
	
	
	function salefactorygoodsku($newssku,$sku,$goods_id)
	{
		$goods = array("DXS","DS","DM","DL","DXL","DXXL","DXXXL");
		$goodsst = array("XS","S","M","L","XL","XXL","XXXL");
		$saleskunums = $this->config->item('saleskunums');    //生成几个销售SKU
		if (!$saleskunums) $saleskunums = 1;
		foreach($goods as $key=>$rs)
		{
			  for ($i = 1; $i <= $saleskunums; $i++) {
					$newarray[$key][$i]["sku"] = $sku."-".$goodsst[$key];
					$newarray[$key][$i]["goods_id"] = $goods_id;
					$newarray[$key][$i]["salesku"] = $newssku."-".$rs;    //判断是否重复生成的SKU
					
				}
		}
		return $newarray;
	}
	
	function channewproductgstauts()
	{

		if($this->input->post('status')+1==5)	//已出图，系统默认标完成，并且自动更新商品到商品列表
		{
			$posts ="";
			$posts['status']=6;
			$posts['overtime']=time();//完成时间
			$posts['startdate']=date("Y-m-d");//商品上架开始计算提成时间
			$enddate = date("Y-m-d",time()+90*86400);
			$posts['enddate']=$enddate;//商品上架开始计算提成时间

			$posts['overuser']=$_COOKIE["username"];
			$this->db->update('db_product_develop',$posts,"id='".$this->input->post('id')."'");			//更新状态
			$rsdb = $this->fun->getdatabasesdetail('db_product_develop','AND id='.$this->input->post('id'));
			$_POST = "";
			$_POST["subsku"] =array("0"=>$rsdb["sku"]);
			$_POST["sku"] = $rsdb["sku"];
			$_POST["goods_name"] = $rsdb["name"];
			$_POST["en_goods_name"] = $rsdb["en_name"];
			$_POST["bigclassID"] =28;
			$_POST["secondclassID"] = 27;
			$_POST["ThreeclassID"] = 0;
			$_POST["costprice"] = $rsdb["samplecosprice"];
			$_POST["procurement"] = 15;
			$_POST["inventory_day"] =15;
			$_POST["weight"] = $rsdb['weight']?$rsdb['weight']:400;
			$_POST["pd_length"] = 0;
			$_POST["pd_width"] = 0;
			$_POST["pd_height"] = 0;
			$_POST["sellprice"] = $rsdb["saleprice"];
			$_POST["pd_declare_value"] = 60;
			$_POST["goodstypeID"] = 7;
			$_POST["sale_status"] = 1;
			$_POST["supplier"] = $rsdb["supplier"];
			$_POST['buyer']	= $rsdb["createName"];
			$_POST['checkman']  = $rsdb["createName"];
			
			$bodystandard =  $rsdb["bodystandard"];
			if($rsdb["qualitymemo"])
			{
				$bodystandard.="+".$rsdb["qualitymemo"];
			}

			$_POST["standard"] = $bodystandard;

			
			$_POST["fabricinfo"] =$rsdb["ck"];
			$_POST["memo"] = $rsdb["samplememo"];
			$_POST["wages"] = $rsdb["wages"];
			$_POST["bulkprice"] = $rsdb["bulkprice"];
			
			$parentID = $this->saveparent();//保存父商品
			$goods_id = $this->savegoods($parentID);			//再保存子商品信息
			
			

			return true;
		}
		return $this->db->update('db_product_develop',array("status"=>$this->input->post('status')+1,"trialtime"=>time())," id='".$this->input->post('id')."'");
	}
	
	/******************
	** 提交商品维护申请
	**  1、供货商是外采购
	**  2、商品的采购和开发人员不包括以下人员开发人员
	**************/
	function saveMaintenanceist($goods_id,$memo,$protector)
	{
		$protector = explode(",",$protector);
		$goods_id = substr($goods_id,0,-1);
		$goods_id = explode(",",$goods_id);
	
		$error = "";
		if(count($goods_id)>0)
		{
			foreach($goods_id as $key=>$goodsID)
			{
				$rsdb = $this->fun->getdatabasesdetail('db_goods'," AND goods_id = ".intval($goodsID));
				if($rsdb)
				{
					//如果存在在外采列表，则不进行提交
					$res = $this->fun->getdatabasesdetail('db_external_buy'," AND sku ='".$rsdb['goods_parent_sku']."' ");
					if($res)
					{
						$error.=",".$rsdb['goods_sku'];
					}else{
						if($rsdb['g_supplier'] ==3)
						{
							if(in_array($rsdb['g_buyer'],$protector) || in_array($rsdb['g_checkman'],$protector))
							{
								$error.=",".$rsdb['goods_sku'];
							}else{
								//可能提交申请
								/******
								德国，西班牙，法国：姜
								欧美：邢润华 
								其他：曾月
								假发鞋子：高菲菲
								*********/
								$p_buyer = $this->fun->getexternal_user($_COOKIE["classid"],$_COOKIE["userid"],$rsdb);
								$goods_parentID = $rsdb['goods_parentID'];
								$this->db->update('db_goods_parent',array("p_buyer"=>$p_buyer,"p_checkman"=>$p_buyer,"memo"=>$memo)," p_parent_id='".$goods_parentID."'");
							}
							
						}else{
							$error.=",".$rsdb['goods_sku'];
						}
					}
				}
			}
		}
		if($error)
		{
			return $error;
		}else{
			return 201;
		}
	}
	/******************************
	*** 通过商品ID和仓库ID
	*** 获得该仓库下的商品待发货数量
	*******************************/
	function getsendthegoods($goods_id,$storage_id)
	{
		if($storage_id==1) $shipping_status =5;
		if($storage_id==3) $shipping_status =1;
		if($storage_id==5) $shipping_status =2;
		if($storage_id==6) $shipping_status =3;
		if($storage_id==7) $shipping_status =4;
		

		if(!$shipping_status)
		{
			return 0;
		}
		if($storage_id ==1)
		{
			$sqls=" AND  B.is_nodelivery = 0 ";
		}
			
		$sql = "SELECT sum(goods_number) as goods_number FROM db_order_sell A left join db_order_list B on A.`order_id` = B.order_id where A.`goods_id` = '{$goods_id}' AND B.order_status in (2,3) and B.shipping_status = $shipping_status $sqls";

	
		$res = $this->db->get_one($sql);
		if(!$res['goods_number'])
			return 0;
		else
			return $res['goods_number'];

	}
	/******************************
	*** 通过商品ID，删除商品信息
	*** 
	*******************************/
	function getdelproduct($goods_id)
	{
		$goods_id = intval($goods_id);
		$rsdb = $this->fun->getdatabasesdetail('db_goods'," AND goods_id='".$goods_id."'");
		$res = $this->db->get_where('db_goods',"goods_parent_sku='".$rsdb["goods_parent_sku"]."'")->result_array();
		//判断是否存在订单，如果存在订单，禁止删除
		$OrderInfo =$this->fun->getdatabasesdetail('db_order_sell'," AND goods_id='".$goods_id."'");
		if($OrderInfo)
		{
			//如果产生了订单，直接隐藏
			if(count($res)==1)
			{
				$this->db->update('db_goods_parent',array("p_yz"=>1), 'p_parent_id=' .$rsdb["goods_parentID"]);
			}
			$this->db->update('db_goods',array("yz"=>1), 'goods_id=' . $goods_id);	//隐藏
			return true;
			//die('该SKU已经产生订单！不能删除！如果需要删除！请先修改订单SKU信息！');
		}
		
		$this->db->trans_begin();
		$rsdbgoods = $this->fun->getdatabasesdetail('db_deleted_goods'," AND goods_id='".$goods_id."'");
		if(!$rsdbgoods){
			$this->db->insert("db_deleted_goods",$rsdb);		//将删除的信息先保存备份
		}
		if(count($res)==1)
		{
			//如果为一，则删除父目录商品
			 $this->db->delete('db_goods_parent', 'p_parent_id=' . $rsdb["goods_parentID"]);
		}
		
		//删除日志
		$this->db->delete('db_goods_log', 'types = 1 AND goods_id=' . $goods_id);
		$this->db->delete('db_goods_stock', 'goods_id=' . $goods_id);	//库存删除
		$this->db->delete('db_goods_stock_log', 'goods_id=' . $goods_id);	//库存日志
		$this->db->delete('db_goods_images', 'goods_id=' . $goods_id); //图片留着不删除
		$this->db->delete('db_goods', 'goods_id=' . $goods_id);	//库存是否删除？
		//如果是外采购商品，需要将外采中的SKU终止开发
		

		if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }
		return true;
	}

	function createOverSeaData($sku,$hw=0){
        $goodsinfo=$this->fun->getdatabasesdetail("db_goods"," AND goods_sku= '".$sku."'");
        if($goodsinfo['g_weight']>0){
            $goodsinfo['g_weight']=$goodsinfo['g_weight']/1000;
        }
        if($goodsinfo['g_pd_length']<=0){
            $goodsinfo['g_pd_length']=10;$goodsinfo['g_pd_width']=10;$goodsinfo['g_pd_height']=6;
        }
        $sql="INSERT INTO t_overseaproduct SET ";
		$sql.=" sku='".$sku."'";
		$sql.=" ,name='".$goodsinfo['goods_name']."'";
		$sql.=" ,costprice='".$goodsinfo['g_costprice']."'";
		$sql.=" ,weight='".$goodsinfo['g_weight']."'";
		$sql.=" ,volumenum='0'";
		$sql.=" ,lengthnum='".$goodsinfo['g_pd_length']."'";
		$sql.=" ,widthnum='".$goodsinfo['g_pd_width']."'";
		$sql.=" ,heightnum='".$goodsinfo['g_pd_height']."'";
        if($hw>0){
            $sql.=",hw='".$hw."'";    
        }
		$sql.=" ,opertime='".date("Y-m-d H:i:s")."'";
		$sql.=" ,opername='".$goodsinfo["g_checkman"]."'";
		$userinfo = $this->fun->userinfo($goodsinfo["g_checkman"]);
		$sql.=" ,oper='".$userinfo["id"]."'";
		$this->db->query($sql);
		$id = $this->db->insert_id();
		return $id;
    }

	function saveProductsample()
	{
		
		$status = $this->input->post('MProductstatus');
		if($status==2)
		{
			//当前出样,必须填写开款信息

		}
		
		$id = $this->input->post('MProductID');
		$rsdb = $this->fun->getdatabasesdetail('db_product_develop','AND id='.$id);
		//存工厂开款的物料信息
		$materialcode = $this->input->post('materialcode');	//物料编号
		$materialnum = $this->input->post('materialnum');	//物料数量
		$materialname = $this->input->post('materialname');	//物料名称
		$materialtypename = $this->input->post('materialtypename');	//物料名称
		$materwages = $this->input->post('materwages');	//物料单价
		$marterdw = $this->input->post('marterdw');	//物料单价
		
		if(count($materialcode)>0)
		{
			$newpost = "";
			//先删除原来的物料
			$this->db->delete("db_product_develop_material","develop_id=".$id);
			foreach($materialcode as $key=>$rsmater)
			{
				$newpost[$key]["materialcode"] = trim($rsmater);
				$newpost[$key]["materialnum"] = $materialnum[$key];
				$newpost[$key]["materialname"] = trim($materialname[$key]);
				$newpost[$key]["materialtypename"] = trim($materialtypename[$key]);
				$newpost[$key]["develop_id"] = $id;
				$newpost[$key]["goods_sku"] = trim($rsdb['sku']);
				$newpost[$key]["materwages"] =trim($materwages[$key]);
				$newpost[$key]["marterdw"] =trim($marterdw[$key]);
			}
			
			$this->db->insert_batch("db_product_develop_material",$newpost);
		}
		//存工厂开款的物料信息结束		

		if($status==6)
		{
			//如果已经完成的只需要修改开款信息
			return $id;
		}
		$post["versiondivision"] = $this->input->post('versiondivision');
		$post["wages"] = $this->input->post('wages');
		$post["weight"] = trim($this->input->post('weight'));
		$post["samplecosprice"] = $this->input->post('cosprice');
		$post["bulkprice"] = $this->input->post('bulkprice');
		$bodystandard = implode("+",$this->input->post('bodystandard'));
		$post["qualitymemo"] =addslashes($this->input->post('qualitymemo'));
		$post["bodystandard"] =$bodystandard;
		$post["ck"] = addslashes($this->input->post('ck'));
		$post["samplememo"] = $this->input->post('memo');
		$post["status"] = $status+1;
		//

		if($status+1==3)
		{
		$post["sampleuser"] = $_COOKIE["username"];
		$post["sampletime"] = time();
		}
		if($status+1==4)
		{
		$post["reviewagainpepole"] = $_COOKIE["username"];
		$post["reviewagain"] = time();
		}
		$this->db->update('db_product_develop',$post," id='".$this->input->post('MProductID')."'");
		
		
		if($status+1==3){	//复审提醒
		//设置系统Message提醒
			$taskerman = $this->config->item('reviewagain');
			if($taskerman && $this->config->item('productdevelopopen')==1)
			{
					$randid = $this->message->getMessageNums();	//获取当前存储的条数	
					$packingman = explode("|",$taskerman);
					foreach($packingman as $rs)
					{
						//判断是一厂，还是二厂，提醒的对象不一样
						if($rsdb["supplier"] ==1 && $rs =='徐勇进')
						{
							$postMessageData["message_type"] = $this->message->getMessageType(6);	//【新品开发】复审
							$postMessageData["message"] = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."已经出样,等待你复审"; //消息内容
							$postMessageData["message_toName"] = '徐勇进';	//接收对象姓名
							$postMessageData["isread"] =  $randid;				//同条消息标识
							$postMessageData["url"] = "/product/newproduct?id={$id}";	//点击消息后返回连接
							$this->fun->saveMessage($postMessageData);
						}

						if($rsdb["supplier"] ==2 && $rs =='叶进')
						{
							$postMessageData["message_type"] = $this->message->getMessageType(6);	//【新品开发】复审
							$postMessageData["message"] = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."已经出样,等待你复审"; //消息内容
							$postMessageData["message_toName"] = '叶进';	//接收对象姓名
							$postMessageData["isread"] =  $randid;				//同条消息标识
							$postMessageData["url"] = "/product/newproduct?id={$id}";	//点击消息后返回连接
							$this->fun->saveMessage($postMessageData);
						}
						if($rsdb["supplier"] ==7 && $rs =='外部开发')
						{
							$postMessageData["message_type"] = $this->message->getMessageType(6);	//【新品开发】复审
							$postMessageData["message"] = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."已经出样,等待你复审"; //消息内容
							$postMessageData["message_toName"] = '外部开发';	//接收对象姓名
							$postMessageData["isread"] =  $randid;				//同条消息标识
							$postMessageData["url"] = "/product/newproduct?id={$id}";	//点击消息后返回连接
							$this->fun->saveMessage($postMessageData);
						}
						
					}
			}
		}

		if($status+1==4){	//复审完成提醒，提醒美工出图
		//设置系统Message提醒
			$artistimages = trim($this->config->item('artistimages'));
			if($artistimages && $this->config->item('productdevelopopen')==1)
			{
					$randid = $this->message->getMessageNums();	//获取当前存储的条数	
					$packingman = explode("|",$artistimages);
					foreach($packingman as $rs)
					{
						$postMessageData["message_type"] = $this->message->getMessageType(7);	//【新品开发】复审
						$postMessageData["message"] = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."已经复审,等待出图"; //消息内容
						$postMessageData["message_toName"] = $rs;	//接收对象姓名
						$postMessageData["isread"] =  $randid;				//同条消息标识
						$postMessageData["url"] = "/product/newproduct?id={$id}";	//点击消息后返回连接
						$this->fun->saveMessage($postMessageData);
					}
			}
		}

		return $id;
	}
}

/* End of file Product_m.php */